package za.org.jcicada.comms.impl;

import java.io.IOException;

import za.org.jcicada.comms.IConnection;
import za.org.jcicada.comms.IMessageListener;

/**
 * Abstract base class for bidirectional queues which stores handle to 
 * the message listener.
 * @author rcrida
 */
public abstract class ConnectionBase implements IConnection {

    /** Reference to the listener to notify of new messages */
    private IMessageListener listener;

    @Override
    public void initialize(IMessageListener listener) throws IOException {
        if (this.listener != null) {
            throw new IllegalStateException(String.format("Connection %s already initialized with listener %s", this, this.listener)); 
        }
        this.listener = listener;
    }

    @Override
    public IMessageListener getListener() {
        return listener;
    }

    @Override
    public String toString() {
    	if (listener == null) {
        	return String.format("%s:null", getClass().getSimpleName());
    	} else {
    		String[] nameParts = listener.getClass().getName().split("\\.");
    		return String.format("%s:%s", getClass().getSimpleName(), nameParts[nameParts.length - 1]);
    	}
    }

}
